/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
// win_inputsys.cpp - mouse and keyboard stuff


#include <queue>
#include "../../core/core.h"
#include <Windows.h>
#include "win_inputsys.h"
#include "win_key_list.h"

/*-----------------------------------------------------------------------------
	Input stuff
-----------------------------------------------------------------------------*/

// ----------------  RawInput ------------------
PRAWINPUTDEVICELIST g_pRawInputDeviceList;
PRAWINPUTDEVICE     g_pRawInputDevices;
int                 g_nUsagePage1Usage8Devices;

//
//	InitRawDevices
//
BOOL EWinInputSystem::InitRawDevices(void)
{
	CoreExecuteString(va("input.s3dm	=	{ tx=%d; ty=%d; tz=%d;   rx=%d; ry=%d; rz=%d; }", 0,0,0,0,0,0));
	
	self->state.s3dmin.translate[0]	=	0;
	self->state.s3dmin.translate[1]	=	0;
	self->state.s3dmin.translate[2]	=	0;
	self->state.s3dmin.rotate[0]	=	0;
	self->state.s3dmin.rotate[1]	=	0;
	self->state.s3dmin.rotate[2]	=	0;

	UINT nDevices;
	GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST));
	
	g_pRawInputDeviceList = (PRAWINPUTDEVICELIST) malloc (sizeof(RAWINPUTDEVICELIST) * nDevices);
	
	GetRawInputDeviceList(g_pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST));
	
	g_pRawInputDevices = (PRAWINPUTDEVICE)malloc( nDevices * sizeof(RAWINPUTDEVICE) );
	
	g_nUsagePage1Usage8Devices = 0;


	for(UINT i = 0; i < nDevices; i++)
	{
		if (g_pRawInputDeviceList[i].dwType == RIM_TYPEHID)
		{
			UINT nchars = 300;
			TCHAR deviceName[300];
			if (GetRawInputDeviceInfo( g_pRawInputDeviceList[i].hDevice, RIDI_DEVICENAME, deviceName, &nchars) >= 0) {
				//LOGF("device [%d]: handle = 0x%X name = %s", i, g_pRawInputDeviceList[i].hDevice, deviceName);
				LOGF("device [%d]: handle = 0x%X", i, g_pRawInputDeviceList[i].hDevice);
			}

			RID_DEVICE_INFO dinfo;
			UINT sizeofdinfo = sizeof(dinfo);
			dinfo.cbSize = sizeofdinfo;
			if (GetRawInputDeviceInfo( g_pRawInputDeviceList[i].hDevice,  RIDI_DEVICEINFO, &dinfo, &sizeofdinfo ) >= 0)	{
			
				if (dinfo.dwType == RIM_TYPEHID) {
					RID_DEVICE_INFO_HID *phidInfo = &dinfo.hid;

					int usagePage	= 1;
					int usage		= 8;
					
					if (phidInfo->usUsagePage == usagePage && phidInfo->usUsage == usage) {

						LOGF("  VID        = 0x%X", phidInfo->dwVendorId);
						LOGF("  PID        = 0x%X", phidInfo->dwProductId);
						LOGF("  version    = 0x%X", phidInfo->dwVersionNumber);
						LOGF("  usage page = 0x%X", phidInfo->usUsagePage);
						LOGF("  usage      = 0x%X", phidInfo->usUsage);
						g_pRawInputDevices[g_nUsagePage1Usage8Devices].usUsagePage = phidInfo->usUsagePage;
						g_pRawInputDevices[g_nUsagePage1Usage8Devices].usUsage     = phidInfo->usUsage;
						g_pRawInputDevices[g_nUsagePage1Usage8Devices].dwFlags     = 0;
						g_pRawInputDevices[g_nUsagePage1Usage8Devices].hwndTarget  = NULL;
						g_nUsagePage1Usage8Devices++;
					}
				}
			}
		}
	}

	// Register for input from the devices in the list
	if (RegisterRawInputDevices( g_pRawInputDevices, g_nUsagePage1Usage8Devices, sizeof(RAWINPUTDEVICE) ) == FALSE ) {
		LOG_ERROR("Error calling RegisterRawInputDevices");
		return FALSE;
	}
	
	return TRUE;
}


//
//	FreeRawInputDevices
//
void EWinInputSystem::FreeRawInputDevices(void)
{
	free( g_pRawInputDeviceList );
	free( g_pRawInputDevices );
}


//
//	ProcessWM_INPUTEvent
//
void EWinInputSystem::ProcessWM_INPUTEvent( LPARAM lParam )
{
	RAWINPUTHEADER header;
	UINT size = sizeof(header);
	
	if ( GetRawInputData( (HRAWINPUT)lParam, RID_HEADER, &header,  &size, sizeof(RAWINPUTHEADER) ) == -1) {
		LOG_ERROR("Error from GetRawInputData(RID_HEADER)");
		return;
	}
	else {
		//LOGF("rawEvent.header: hDevice = 0x%X", header.hDevice );
	}

	// Set aside enough memory for the full event
	size = header.dwSize * 2;
	LPRAWINPUT event = (LPRAWINPUT)malloc(size);
	
	if (GetRawInputData( (HRAWINPUT)lParam, RID_INPUT, event, &size, sizeof(RAWINPUTHEADER) ) == -1) {
		LOG_ERROR("Error from GetRawInputData(RID_INPUT)");
		free(event);
		return;
	}
	else {
		if (event->header.dwType == RIM_TYPEHID) {
		
			static BOOL bGotTranslation = FALSE, 
				        bGotRotation    = FALSE;
			static int all6DOFs[6] = {0};
			LPRAWHID pRawHid = &event->data.hid;

			// Translation or Rotation or Buttons packet.
			if (pRawHid->bRawData[0] == 1) // Translation vector
			{
				all6DOFs[0] = (pRawHid->bRawData[1] & 0x000000ff) | ((signed short)(pRawHid->bRawData[2]<<8) & 0xffffff00); 
				all6DOFs[1] = (pRawHid->bRawData[3] & 0x000000ff) | ((signed short)(pRawHid->bRawData[4]<<8) & 0xffffff00); 
				all6DOFs[2] = (pRawHid->bRawData[5] & 0x000000ff) | ((signed short)(pRawHid->bRawData[6]<<8) & 0xffffff00);
				bGotTranslation = TRUE;
			}
			else if (pRawHid->bRawData[0] == 2) // Rotation vector
			{
				all6DOFs[3] = (pRawHid->bRawData[1] & 0x000000ff) | ((signed short)(pRawHid->bRawData[2]<<8) & 0xffffff00); 
				all6DOFs[4] = (pRawHid->bRawData[3] & 0x000000ff) | ((signed short)(pRawHid->bRawData[4]<<8) & 0xffffff00); 
				all6DOFs[5] = (pRawHid->bRawData[5] & 0x000000ff) | ((signed short)(pRawHid->bRawData[6]<<8) & 0xffffff00);
				bGotRotation = TRUE;
			}
			else if (pRawHid->bRawData[0] == 3) // Buttons (display most significant byte to least)
				LOGF("Button mask: %.2x %.2x %.2x",(unsigned char)pRawHid->bRawData[3],(unsigned char)pRawHid->bRawData[2],(unsigned char)pRawHid->bRawData[1]);

			if (bGotTranslation && bGotRotation)
			{
				bGotTranslation = bGotRotation = FALSE;
				
				self->state.s3dmin.translate[0]	=	all6DOFs[0];
				self->state.s3dmin.translate[1]	=	all6DOFs[1];
				self->state.s3dmin.translate[2]	=	all6DOFs[2];
				self->state.s3dmin.rotate[0]	=	all6DOFs[3];
				self->state.s3dmin.rotate[1]	=	all6DOFs[4];
				self->state.s3dmin.rotate[2]	=	all6DOFs[5];
							
				CoreExecuteString(va("input.s3dm	=	{ tx=%d; ty=%d; tz=%d;   rx=%d; ry=%d; rz=%d; }", 
					all6DOFs[0], all6DOFs[1], all6DOFs[2],
					all6DOFs[3], all6DOFs[4], all6DOFs[5]	));
				
				//LOGF("all6DOFs: %d %d %d ", all6DOFs[0], all6DOFs[1], all6DOFs[2]);
				//LOGF(          "%d %d %d",  all6DOFs[3], all6DOFs[4], all6DOFs[5]);
			}
		}
	}
	
	free(event); 
}

